在dataFrame中,我们通常可以通过调用pd.concat函数做行合并。在series中,做合并通常可以使用cat函数。举例如下: 1、连接对象仅是一个字符
>>> import pandas as pd
>>> import numpy as np
>>> s = pd.Series(['a', 'b', 'c', 'd'])
>>> s
0 a
1 b
2 c
3 d
dtype: object
>>> s.str.cat(sep=',')
'a,b,c,d'
# 如果中间有nan,不特殊说明,通常直接忽略掉
>>> t = pd.Series(['a', 'b', np.nan, 'd'])
>>> t.str.cat(sep=',')
'a,b,d'
# 通过指定na_rep参数,做连接时,nan被替换
>>> t.str.cat(sep=',', na_rep='-')
'a,b,-,d'
2、连接对象是一个list
>>> u = pd.Series(['b', 'd', 'a', 'c'], index=[1, 3, 0, 2])
>>> s
0 a
1 b
2 c
3 d
dtype: object
>>> u
1 b
3 d
0 a
2 c
dtype: object
# 如果不指定join参数,则还是会按照list列表中的
# 顺序依次做连接
>>> s.str.cat(u)
0 ab
1 bd
2 ca
3 dc
dtype: object
# 通过指定连接方式,join有left,right,inner,outer四种
# 连接方式,分别安装index对号连接
>>> s.str.cat(u, join='left')
0 aa
1 bb
2 cc
3 dd
dtype: object
哈哈,以上就是python小工具关于cat函数的使用的介绍,有兴趣欢迎关注公众号:python小工具。一起学习python和pandas
|